package com.luboyan.CBillbill.service.user.following.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luboyan.CBillbill.exception.ConditionException;
import com.luboyan.CBillbill.mapper.user.following.FollowingGroupMapper;
import com.luboyan.CBillbill.dao.user.following.FollowingGroup;
import com.luboyan.CBillbill.service.user.following.FollowingFGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.luboyan.CBillbill.util.enums.UserInfoEnum.USER_FOLLOWING_GROUP_TYPE_USER;

@Service
public class FollowingGroupServiceImpl implements FollowingFGroupService {

    @Autowired
    private FollowingGroupMapper followingGroupMapper;

    /**
     * 通过类型获取相应的分组信息
     */
    @Override
    public FollowingGroup getByType(String type) {
        QueryWrapper<FollowingGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        return followingGroupMapper.selectOne(queryWrapper);
    }

    /**
     * 用于配合UserFollowingService的方法
     * 通过groupId对应分组表中的id查询组是否存在
     */
    @Override
    public FollowingGroup getById(Long id) {
        return followingGroupMapper.selectById(id);
    }

    /**
     * 用于配合UserFollowingService的方法
     * 查询用户所有的关注分组
     */
    @Override
    public List<FollowingGroup> getFollowingGroupByUserId(Long userid) {
        QueryWrapper<FollowingGroup> queryWrapper = new QueryWrapper<>();
        List<String> list = Arrays.asList("0", "1", "2");
        queryWrapper.eq("userId", userid).
                or().in("type", list);
        return followingGroupMapper.selectList(queryWrapper);
    }

    /**
     * 添加用户关注分组
     *
     * @return 返回新分组的id
     */
    @Override
    public Long addUserFollowingGroups(FollowingGroup followingGroup) {
        QueryWrapper<FollowingGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", followingGroup.getName());
        FollowingGroup dbfollowingGroup = followingGroupMapper.selectOne(queryWrapper);
        if (dbfollowingGroup != null) {
            throw new ConditionException("分组已存在！");
        }
        followingGroup.setCreateTime(new Date());
        followingGroup.setType(USER_FOLLOWING_GROUP_TYPE_USER.getParameter());
        followingGroupMapper.insert(followingGroup);

        return followingGroup.getId();
    }

    /**
     * 获取用户所有分组信息
     */
    @Override
    public List<FollowingGroup> getUserFollowingGroups(Long userId) {
        return followingGroupMapper.selectList
                (new QueryWrapper<FollowingGroup>().eq("userId", userId));
    }
}
